package com.lagou.rpc.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZkUtil {

    private CuratorFramework zkClient;

    private static final String path = "/lg-rpc";

    private List<String> addressList = new ArrayList<>();

    public ZkUtil() {
        zkClient = getZkClient();
    }

    // 创建客户端
    public static CuratorFramework getZkClient(){

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("106.75.13.174:2181")
                .sessionTimeoutMs(1000)
                .connectionTimeoutMs(1000)
                .retryPolicy(retryPolicy)
                .namespace("base")
                .build();
        client.start();
        return client;
    }

    // 注册服务
    public void register(String serviceAddress){

        try {
            // 节点地址
            String addressPath = path + "/" + serviceAddress;

            zkClient.create().creatingParentContainersIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(addressPath, (System.currentTimeMillis() + ":" + 0).getBytes(StandardCharsets.UTF_8));

            System.out.println("服务注册成功："+ addressPath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取所有节点内容信息
    public Map<String, String> getAddressList(){

        List<String> nodeList = null;

        Map<String, String> nodeInfoMap = new HashMap<>();

        try {
            nodeList = zkClient.getChildren().forPath(path);

            for (String address : nodeList) {

                String nodePath = path + "/" + address;

                String nodeData = new String(zkClient.getData().forPath(nodePath), StandardCharsets.UTF_8);


                nodeInfoMap.put(address, nodeData);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodeInfoMap;
    }

    // 更新服务
    public void updateNodeData(String node, String data) throws Exception {
        String nodePath = path + "/" + node;

        // 状态信息
        Stat stat = new Stat(); //0
        zkClient.getData().storingStatIn(stat).forPath(nodePath);

        int version = zkClient.setData().withVersion(stat.getVersion())
                .forPath(nodePath, data.getBytes(StandardCharsets.UTF_8)).getVersion();
        byte[] bytes2 = zkClient.getData().forPath(nodePath);
    }
}
